#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
CEGUI布局编辑器
用于编辑CEGUI 0.4的XML布局文件
支持跟随Windows系统日夜主题自动切换
"""

import sys
import os
import winreg
from PyQt5.QtWidgets import QApplication, QStyleFactory
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import QColor
from gui_editor import MainWindow

def get_windows_theme():
    """获取Windows系统当前主题设置（深色/浅色）"""
    try:
        registry = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
        key = winreg.OpenKey(registry, r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize")
        # AppsUseLightTheme=0表示深色主题，=1表示浅色主题
        value, _ = winreg.QueryValueEx(key, "AppsUseLightTheme")
        return "light" if value == 1 else "dark"
    except Exception:
        # 如果出错，默认返回浅色主题
        return "light"

def apply_theme(app, theme):
    """应用主题到应用程序"""
    if theme == "dark":
        # 设置深色主题
        app.setStyle("Fusion")
        dark_palette = app.palette()
        dark_palette.setColor(dark_palette.Window, QColor(53, 53, 53))
        dark_palette.setColor(dark_palette.WindowText, QColor(255, 255, 255))
        dark_palette.setColor(dark_palette.Base, QColor(25, 25, 25))
        dark_palette.setColor(dark_palette.AlternateBase, QColor(53, 53, 53))
        dark_palette.setColor(dark_palette.ToolTipBase, QColor(255, 255, 255))
        dark_palette.setColor(dark_palette.ToolTipText, QColor(255, 255, 255))
        dark_palette.setColor(dark_palette.Text, QColor(255, 255, 255))
        dark_palette.setColor(dark_palette.Button, QColor(53, 53, 53))
        dark_palette.setColor(dark_palette.ButtonText, QColor(255, 255, 255))
        dark_palette.setColor(dark_palette.BrightText, QColor(255, 0, 0))
        dark_palette.setColor(dark_palette.Link, QColor(42, 130, 218))
        dark_palette.setColor(dark_palette.Highlight, QColor(42, 130, 218))
        dark_palette.setColor(dark_palette.HighlightedText, QColor(0, 0, 0))
        app.setPalette(dark_palette)
    else:
        # 重置为系统默认浅色主题
        app.setStyle("Fusion")
        app.setPalette(app.style().standardPalette())

def check_theme_change(app, last_theme):
    """检查主题是否变化，并在变化时应用新主题"""
    current_theme = get_windows_theme()
    if current_theme != last_theme[0]:
        apply_theme(app, current_theme)
        last_theme[0] = current_theme
    # 继续定时检查
    QTimer.singleShot(1000, lambda: check_theme_change(app, last_theme))

def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 初始应用主题
    current_theme = get_windows_theme()
    apply_theme(app, current_theme)
    
    # 使用列表存储当前主题以便在回调函数中修改
    last_theme = [current_theme]
    
    # 定时检查主题变化
    QTimer.singleShot(1000, lambda: check_theme_change(app, last_theme))
    
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()